import {
  appGetStorage,
  appRemoveStorage,
  appSetStorage,
} from "@/utils/storage";
import {
  TOKEN_STORAGE_KEY,
  USERINFO_STORAGE_KEY,
  PUBUSERINFO_STORAGE_KEY,
} from "@/const/application/auth";
import { removeToken, setToken } from "@/utils/auth";
import { pubUserInfo } from "@/service/api/sp-store";

const state = {
  token: appGetStorage(TOKEN_STORAGE_KEY),
  userInfo: appGetStorage(USERINFO_STORAGE_KEY),
  pubUserInfo: appGetStorage(PUBUSERINFO_STORAGE_KEY),
  login_code: null,
};

const mutations = {
  SET_TOKEN: (state, data) => {
    state.token = data;
  },
  CLEAR_TOKEN: (state) => {
    state.token = null;
  },
  SET_USER_INFO: (state, data) => {
    state.userInfo = data;
  },
  CLEAR_USER_INFO: (state) => {
    state.userInfo = null;
  },
  SET_PUBUSER_INFO: (state, data) => {
    state.pubUserInfo = data;
  },
  CLEAR_PUBUSER_INFO: (state) => {
    state.pubUserInfo = null;
  },
  SET_LOGIN_CODE: (state, data) => {
    state.login_code = data;
  },
  CLEAR_LOGIN_CODE: (state) => {
    state.login_code = null;
  },
};

const actions = {
  setTokenAction({ commit }, data) {
    setToken(data);
    commit("SET_TOKEN", data);
	
	pubUserInfo().then((res) => {
		appSetStorage(PUBUSERINFO_STORAGE_KEY, res);
		commit("SET_PUBUSER_INFO", res);
	});
  },
  clearTokenAction({ commit }) {
    removeToken(TOKEN_STORAGE_KEY);
    commit("CLEAR_TOKEN");
	
	appRemoveStorage(PUBUSERINFO_STORAGE_KEY);
	commit("CLEAR_PUBUSER_INFO");
  },
  setUserInfoAction({ commit }, data) {
    appSetStorage(USERINFO_STORAGE_KEY, data);
    commit("SET_USER_INFO", data);
  },
  clearUserInfoAction({ commit }) {
    appRemoveStorage(USERINFO_STORAGE_KEY);
    commit("CLEAR_USER_INFO");
  },
  setLoginCodeAction({ commit }, data) {
    commit("SET_LOGIN_CODE", data);
  },
  clearLoginCodeAction({ commit }) {
    commit("CLEAR_LOGIN_CODE");
  },
};

const getter = {
  token(state) {
    return state.token;
  },
  isLogin(state) {
    return !!state.token;
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getter,
};
